package com.godyao.framework.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import com.godyao.framework.beans.BeansException;
import com.godyao.framework.beans.factory.DisposableBean;
import com.godyao.framework.beans.factory.config.BeanDefinition;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 销毁方法适配器(接口和配置)
 * @author missw
 */
public class DisposableBeanAdapter implements DisposableBean {
    private final Object bean;

    private final String beanName;

    private String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition bd) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = bd.getDestroyMethodName();
    }

    @Override
    public void destroy() throws Exception {
        // 1.实现接口DisposableBean 调用实现类的destroy方法
        if (bean instanceof DisposableBean) {
            ((DisposableBean) bean).destroy();
        }

        // 2.通过反射调用xml配置的destroy-method 两种销毁方式若同时存在则指销毁一次
        if (StrUtil.isNotBlank(destroyMethodName) && !(bean instanceof DisposableBean && "destroy".equals(this.destroyMethodName))) {
            Method destroyMethod = bean.getClass().getMethod(destroyMethodName);
            if (null == destroyMethod) {
                throw new BeansException("Couldn't find a destroy method named '" + destroyMethodName + "' on bean with name '" + beanName + "'");
            }
            destroyMethod.invoke(bean);

        }
    }
}
